package com.yanqu.road.server.channelserver.manager.activity.luckydraw;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChannelLuckyDrawMgr extends TempMgr {

    private static final Map<Integer, ChannelLuckyDrawActivity> activityMap = new ConcurrentHashMap<>();

    public static ChannelLuckyDrawActivity getActivity(int activityId) {
        if (!activityMap.containsKey(activityId)) {
            synchronized (activityMap) {
                if (!activityMap.containsKey(activityId)) {
                    ChannelLuckyDrawActivity activity = new ChannelLuckyDrawActivity(activityId);
                    activityMap.put(activityId, activity);
                }
            }
        }
        return activityMap.get(activityId);
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {

        for (ChannelLuckyDrawActivity activity : activityMap.values()) {
            try {
                activity.save();
            } catch (Exception e) {
                getLogger().error("error : ", e);
            }
        }

        // 移除过期
        long now = System.currentTimeMillis();
        for (Map.Entry<Integer, ChannelLuckyDrawActivity> entry : activityMap.entrySet()) {
            ChannelLuckyDrawActivity activity = entry.getValue();
            ActivityInfo activityInfo = activity.getConfig().getActivityInfo();
            if (now > activityInfo.getEndShowTime() * 1000 + DateHelper.DAY_MILLIONS) {
                activityMap.remove(entry.getKey());
                getLogger().debug("remove expire lucky draw activity {}.", entry.getKey());
            }
        }

        return true;
    }
}
